package main

import (
	"bufio"
	"compress/gzip"
	"flag"
	"fmt"
	"golang/oname"
	"io/ioutil"
	"log"
	"math"
	"net/url"
	"os"
	"reflect"
	"strings"
	"sync"
	"time"
	"unsafe"
)

func testScanner() {
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		fmt.Println(scanner.Text()) // Println will add back the final '\n'
	}
	if err := scanner.Err(); err != nil {
		fmt.Fprintln(os.Stderr, "reading standard input:", err)
	}
}

type i1 struct {
}

func (ai1 i1) X() {
	fmt.Println(ai1)
}
func testSi() {
	si.D(i1{})
}

type s struct {
	a int
}

func (as *s) get() {

}

// Eater defines how people eat
type Eater interface {
	tool() int
	way() string
}

type emptyEater int

func (e *emptyEater) tool() int {
	return 0
}
func (e *emptyEater) way() string {
	return `nil eater`
}

// AEater is a eater
type AEater struct {
	Eater
}

// BEater is
type BEater struct {
	*AEater
	a, b int
}

func getEmptyEater() *emptyEater {
	var aa emptyEater = 1
	return &aa
}
func needEater(a Eater) {

}
func tAeater() {
	var aeater = AEater{Eater: getEmptyEater()}
	needEater(aeater)
}
func tBeater() {
	var aeater = AEater{Eater: getEmptyEater()}
	var abeater = BEater{AEater: &aeater}
	fmt.Println(abeater.a)
}

///////////////////////////////////////
type sInterface interface {
	f()
}

type isInterface struct {
	a, b int
}

func (a *isInterface) f() {
	fmt.Println(a.a, a.b)
}

type haveIn struct {
	sInterface
}

func t() {
	var aa = &isInterface{a: 333, b: 444}
	var haveIn = &haveIn{aa}
	haveIn.f()
	var bb sInterface = aa
	bb.f()
	var cc = bb.(*isInterface)
	cc.f()
}

///
func toname() {
	ll.TT()
}

///
type pi *int
type haoba struct {
	i int
}

func (a *haoba) Geg(i int) (jj, ii int) {
	fmt.Println("geg called", i)
	return 1, 2
}
func treflect() {
	var a pi = new(int)
	e := reflect.ValueOf(a).Elem()
	e.SetInt(34)
	fmt.Println(*a)
}

func getType() {
	a := 'a'
	ta := reflect.TypeOf(a)
	sta := fmt.Sprintf("%v", ta)
	fmt.Println(sta)

	ns := "abcde"
	ab := ns[0]
	tab := reflect.TypeOf(ab)
	stab := fmt.Sprintf("%v", tab)
	fmt.Println(stab)

	t := reflect.TypeOf('/')
	st := fmt.Sprintf("%v", t)
	fmt.Println(st)

	// str := "aafasfb"
	// if str[0] == 'a' {

	// }
	// a = 'a'
	// if str[0] == a {

	// }

}

func setViaValue() {
	phaoba := &haoba{i: 1}
	v := reflect.ValueOf(phaoba).Elem()
	t := v.Type()
	var j = 4
	vj := reflect.ValueOf(j)
	for i := 0; i < t.NumField(); i++ {
		f := t.Field(i)
		fv := v.FieldByName(f.Name)
		d := unsafeValueOf(fv)
		d.Set(vj)
	}
	fmt.Println("we can do this ", phaoba.i)
	fmt.Println("and then we will do a function call-----")
	fmt.Println("use elem:")
	n := v.NumMethod()
	fmt.Println("the num of elem methods is ", n)
	v = reflect.ValueOf(phaoba)
	fmt.Println("then lets try v:")
	n = v.NumMethod()
	fmt.Println("the num of v methods is ", n)
	aa := v.MethodByName("Geg").Call([]reflect.Value{reflect.ValueOf(j)})
	for _, iadsf := range aa {
		fmt.Println(iadsf)
	}
}
func tNop() {
	ahaoba := haoba{i: 1}
	v := reflect.ValueOf(ahaoba)
	t := v.Type()
	var j = 4
	vj := reflect.ValueOf(j)
	for i := 0; i < t.NumField(); i++ {
		f := t.Field(i)
		fv := v.FieldByName(f.Name)
		d := unsafeValueOf(fv)
		d.Set(vj)
	}
	fmt.Println(ahaoba.i)
}
func pobokeyuan() {
	phaoba := &haoba{i: 1}
	v := reflect.ValueOf(phaoba).Elem()
	t := v.Type()
	var j = 4
	vj := reflect.ValueOf(j)
	f := t.Field(0)
	fv := v.FieldByName(f.Name)
	d := unsafeValueOf(fv)
	d.Set(vj)
	fmt.Println("we can do this ", phaoba.i)
}
func unsafeValueOf(val reflect.Value) reflect.Value {
	uptr := unsafe.Pointer(val.UnsafeAddr())
	return reflect.NewAt(val.Type(), uptr).Elem()
}

func testChannel() {
	var ch chan int
	var i int
	go func() {
		i = <-ch
	}()
	time.Sleep(time.Second * 3)
}

func tTime() {
	a := time.Time{}
	fmt.Println(a.IsZero())
}

func tfunc() {
	a := tTime
	b := fmt.Sprintf("%v", a)
	c := fmt.Sprintf("%v", tTime)
	if b == c {
		fmt.Println("OK")
	}
}

func tURL() {
	url := &url.URL{Path: "///path"}
	str := url.String()
	fmt.Println(str)
}

func tConversion() {
	var i byte = 1
	a := 'a'
	i = byte(a)
	fmt.Println(i)
}

func tPool() {
	aPool := sync.Pool{New: func() interface{} { return "New Str" }}
	aPool.Put("explicit str")
	one := aPool.Get().(string)
	fmt.Println(one)
	one = aPool.Get().(string)
	fmt.Println(one)

	aPool.Put("explicit two str")
	time.Sleep(time.Minute * 2)
	time.Sleep(time.Second * 10)

	one = aPool.Get().(string)
	fmt.Println(one)

}

func tstrings() {
	ss := []string{"a", "b", "c"}
	rs := strings.Join(ss, "::")
	fmt.Println(rs)
}

// func qipa() {
// 	ptArgs := fasthttp.AcquireArgs()
// 	ptArgs.Set("model_id", "global")
// 	ptArgs.SetUint("no_deal", 0)
// 	ptArgs.SetBytesV("feats", []byte("aa"))

// 	if !true {
// 		// get uniq cats & adids
// 	} else {
// 		fmt.Println("ptArgs", ptArgs)
// 		newArgs := fasthttp.AcquireArgs()
// 		newArgs.Set("test", "test")
// 		go func() {
// 			fmt.Println("ptArgs 1", ptArgs)
// 			fmt.Println("new_args 1", newArgs)
// 		}()

// 		go func(a *fasthttp.Args, b *fasthttp.Args) {
// 			fmt.Println("ptArgs 2", a)
// 			fmt.Println("new_args 2", b)
// 		}(ptArgs, newArgs)
// 	}
// }

type pst struct {
	data []byte
}

func (p *pst) String() string {
	return string(p.data)
}

var cha = make(chan int)

func tpool() {
	p := &sync.Pool{
		New: func() interface{} {
			return &pst{}
		},
	}
	a := p.Get().(*pst)
	a.data = []byte("asdfasd")
	fmt.Println(",", a)
	go func() {
		time.Sleep(time.Second * 2)
		fmt.Println("core goroutine begin")
		go func() {
			fmt.Printf("__%T\n", a)
		}()
	}()
	a.data = nil
	fmt.Println("over")
}

func ttpye() {
	// type zheng int
	// var i zheng = 1
	// j := 0
	// j = i
}

type fun func()

func tfun(afun fun) {

}

func sfun() fun {
	return func() {

	}
}

func ttfun() {
	tfun(sfun())
}

type xiao struct {
}

func (xiao) String() string {
	return `yi zhi xiao`
}

func tstring() {
	// var x xiao
	// fmt.Println([]byte(x))
}

func tsprintf() {
	s := fmt.Sprintf("%s,.,.,.%s,.,.,.%s,.,.,.", "name", "xiaoming", "20")
	fmt.Println(s)
}

func tinterface() {
	var a []string
	a = append(a, "a")
	a = append(a, "b")
	fmt.Println(a)
	var b interface{} = a
	c := b.([]interface{})
	fmt.Println(c)
}

type sss struct {
	a int
	b int
}

func tpointer() {
	i := 1
	var aa *int
	*aa = i
}
func txx(a []int) []int {

	return a
}

type fmta struct {
	a int
}

func tslic() {
	b := []fmta{fmta{1}, fmta{2}}
	b[0].a = 3
	fmt.Println(b)
}

type tm struct {
	a int
}

func tmap() {
	m := make(map[string]tm)
	atm := tm{1}
	m["a"] = atm
}

type stringArray []string

func (a *stringArray) Set(s string) error {
	*a = append(*a, s)
	return nil
}

func (a *stringArray) String() string {
	return strings.Join(*a, ",")
}

// func tstrtime() {
// 	t := time.Now()
// 	sformat := "%Y-%m-%d_%H"
// 	datetime := strftime(sformat, t)
// 	fmt.Println(datetime)
// }

func topenfile() {
	openFlag := os.O_WRONLY | os.O_CREATE
	gzipEnabled := 2
	if gzipEnabled == 1 {
		openFlag |= os.O_EXCL
	} else if gzipEnabled == 2 {
		openFlag |= os.O_APPEND
	}
	out, err := os.OpenFile("absFilename", openFlag, 0666)
	defer out.Close()
	if err != nil {
		if os.IsExist(err) {
			log.Printf("INFO: file already exists: %s", "absFilename")
			return
		}
		log.Fatalf("ERROR: %s Unable to open %s", err, "absFilename")
	}
	out.WriteString("--")
}

func toFileGzip() {
	str := "123456789abcdefghijklmnopqrstuvwxyz"
	bb := []byte(str)
	openFlag := os.O_WRONLY | os.O_CREATE | os.O_EXCL
	f, _ := os.OpenFile("shishi.gz", openFlag, 0666)
	w, _ := gzip.NewWriterLevel(f, 9)
	w.Write(bb)
	w.Write([]byte{'\n'})
	w.Close()
	f.Close()

	f, _ = os.OpenFile("shishi.gz", os.O_RDONLY, 0666)
	gf, _ := gzip.NewReader(f)
	b, _ := ioutil.ReadAll(gf)
	fmt.Println(string(b))
}

func gzip2Bytes() {
	str := "123456789abcdefghijklmnopqrstuvwxyz"
	bb := []byte(str)
	openFlag := os.O_WRONLY | os.O_CREATE | os.O_EXCL
	f, _ := os.OpenFile("shishi.gz", openFlag, 0666)
	w, _ := gzip.NewWriterLevel(f, 9)
	w.Write(bb)
	w.Write([]byte{'\n'})
	w.Close()
	f.Close()
	f, _ = os.OpenFile("shishi.gz", os.O_RDONLY, 0666)
	gf, _ := gzip.NewReader(f)
	b, _ := ioutil.ReadAll(gf)
	fmt.Println(string(b))

}
func KmpMatch(astring []byte, bstring []byte) int {
	i, j := 1, 0
	next := make([]int, len(bstring))
	next[0] = 0
	for i < len(bstring) {
		if bstring[i] == bstring[j] {
			next[i] = j + 1
			i++
			j++
		} else if j == 0 {
			next[i] = 0
			i++
		} else {
			j = next[j]
		}
	}
	i, j = 0, 0
	for i < len(astring) {
		if astring[i] == bstring[j] {
			if j == len(bstring)-1 {
				return i
			}
			i++
			j++
		} else {
			if j > 0 {
				j = next[j-1]
			} else {
				j = 0
				i++
			}
		}
	}
	return 0
}

type tttttmap struct {
	a map[string]int
}

func tttboolflag() {
	gzipLevel := flag.Int("gzip-level", 6, "gzip compression level (1-9, 1=BestSpeed, 9=BestCompression)")
	gzipEnabled := flag.Bool("gzip", false, "gzip output files.")

	flag.Parse()
	fmt.Println(*gzipLevel, *gzipEnabled)
}
func frommsecondsgethour() {
	atime := time.Unix(1478682937, 0)
	fmt.Println(atime.Year(), atime.Month(), atime.Day(), atime.Hour(), atime.Minute(), atime.Second())
}
func getPubid(absPath string) string {
	ss := strings.Split(absPath, "/")
	filename := ss[len(ss)-1]
	return strings.Split(filename, ".")[0]
}
func tinit() {
	type s struct {
		a [][]int
	}
	var ss s
	b := make([]int, 1)
	b[0] = 123
	ss.a = append(ss.a, b)
	fmt.Println(ss.a)
}
func cos(a, b map[string]int) float64 {
	var zong int
	var xia1 float64
	for _, v := range a {
		zong += (v) * (v)
	}
	xia1 = math.Sqrt(float64(zong))
	var xia2 float64
	zong = 0
	for _, v := range b {
		zong += (v) * (v)
	}
	xia2 = math.Sqrt(float64(zong))
	xia1 = xia1 * xia2
	zong = 0
	lena := len(a)
	var i int
	for k, v := range a {
		if z, ok := b[k]; ok == true {
			zong = zong + (z * v)
		} else {
			i++
		}
	}
	fmt.Println(zong, xia1, lena, i)
	return float64(zong) / xia1
}

func asfas() {
	s := "zaa"
	ss := "fmt"
	if s < ss {
		fmt.Println("ok")
	}
}
func boo() {
	fmt.Println(1 << 20)
}
func slic() {
	d := "20161221"
	d1 := d[0:8]
	fmt.Println(d1)
}
func tswitch() {
	var a = 1
	switch a {
	case 1:
		log.Println(1)
	default:
		log.Println("....")
	}
}
func tselect() {
	c := make(chan int)
	go func() {
		for {
			time.Sleep(1 * time.Second)
			c <- 1
		}
	}()
	for {
		select {
		case ic := <-c:
			fmt.Println(ic)
			break
		}
	}
}
func tslice() {
	var a []string
	log.Println(len(a))
}

type ReceiveList struct {
	MsgOK  []string
	MsgErr []string
}

func tmappointer() {
	r := make(map[string]*ReceiveList)
	if list, found := r["transID"]; found == true {
		list.MsgOK = append(list.MsgOK, "12121")
	} else {
		r["transID"] = &ReceiveList{MsgOK: []string{"123123"}}
	}
	log.Println(len(r))
}

func tnil() {
	var a []string
	b := len(a)
	fmt.Println("b==0 -->", b == 0)
}
func tmapa() {
	var a = make(map[string][]string)
	a["bbb"] = []string{"xxxx"}
	fmt.Println(&a)
}
func main() {
	tmapa()
	// tmappointer()

	// tselect()
	// tswitch()
	// slic()
	// a := make(map[string]int)
	// b := make(map[string]int)
	// a["a"] = 1000
	// a["b"] = 1000
	// a["c"] = 1000
	// a["d"] = 2000
	// b["d"] = 2000

	// c := cos(a, b)
	// fmt.Println(c)
	// tinit()
	// fmt.Println(getPubid("/hdd1/ssp-log/asdfasdf.1234234.123412"))
	// frommsecondsgethour()
	// a := make([][]int, 1)
	// a[0] = append(a[0], 1)
	// fmt.Println(a)
	// toFileGzip()
	// tttboolflag()
	// tstructmap()
	// b := bytes.Index([]byte(`"apubID":"fmtabcabcabcabcabc11",name=wsy`), []byte("pubID"))
	// fmt.Println(b)
	// toBufferGzip()
	// topenfile()
	// tstrtime()
	// tflag()
	// tmap()
	// tpointer()
	// tinterface()
	// var a uint32 = 111
	// var b = float64(a)
	// fmt.Println(b)
	// twfile()
	// tmap()
	// tslice()
	// turl()
	// tsprintf()
	// tpool()
	// runtime.GC()
	// fmt.Println("gc")

	// time.Sleep(time.Second * 3)
	// qipa()
	// time.Sleep(time.Second * 1)

	// tstrings()
	// tPool()
	// tConversion()
	// tURL()
	// toname()
	// log.Fatal("asfasd")
	// t()
	//treflect()
	// setViaValue()
	// tNop()
	// pobokeyuan()
	// testChannel()
	// tTime()
	// tfunc()
	// getType()
	// sigChan := make(chan os.Signal, 1)
	// signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
	// fmt.Println(syscall.SIGTERM)
	// var signals = [...]string{}
	// fmt.Println(len(signals))
	// select {
	// case <-sigChan:
	// 	fmt.Println("out")
	// 	os.Exit(0)
	// }
}

func turl() {
	// bs := []byte(`www.www.www/#`)
	urlb := read3("./urlBytes")
	u, e := url.Parse(string(urlb))
	if e != nil {
		os.Exit(1)
	}
	fmt.Println("--")
	fmt.Println(u.Host)
	fmt.Println(u.Path)
	// ps := proto.String(u.Host + u.Path)
	// fmt.Println(*ps)
	// fmt.Println(ps)

	// ss := proto.String(u.Path)
	// if *ss == u.Path {
	// 	fmt.Println("==")
	// }
	// fmt.Println(u.Path)
	// feats := &structs.Feats{
	// 	UrlPath: proto.String(u.Path),
	// }
	// featsBytes, _ := proto.Marshal(feats)

	// fmt.Println(string(featsBytes))
	// for i, j := range featsBytes {
	// 	fmt.Println(i, j)
	// }
	// an := &structs.Feats{}

	// proto.Unmarshal(featsBytes, an)

	// fmt.Println(an)

}

func twfile() {
	f, _ := os.Create("./test.log")
	f.Write([]byte("aa"))

}
func read3(path string) []byte {
	fi, err := os.Open(path)
	if err != nil {
		panic(err)
	}
	defer fi.Close()
	fd, err := ioutil.ReadAll(fi)

	// fmt.Println(string(fd))
	return fd
}

func tarray() {
	a := [2]int{1, 2}
	a[0] = 3
	fmt.Println(a)
	b := a
	b[0] = 4
	fmt.Println(a)
	fmt.Println(b)
}
